package jmm.threadPool.completionService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class CompletionServiceDemo1_1 {

    public static void main(String[] args) {
        // 创建线程池
        ExecutorService executor =
                Executors.newFixedThreadPool(3);

        CompletionService<String> completionService = new ExecutorCompletionService(executor);

        List<String> taskList = new ArrayList(5);
        taskList.add("w");
        taskList.add("s");
        taskList.add("C");

        taskList.stream().forEach(task->{
            completionService.submit(()->{
                System.out.println("开始"+task);
                if (task.equals("s")){
                    Thread.sleep(5000);
                }
                System.out.println("===="+task);
                return task;
            });
        });

        String str = null;
        // 跟CompletionServiceDemo5 区别是，可以先打印出结果C，但是不管那个，====C都在输出====s结果前已经打印出啦。
        // 即：不管哪种方式，不会影响数据的执行，阻塞的任务不影响其他任务的执行，只是差异在获取任务执行的结果
/*        for (int i = 0; i < taskList.size(); i++) {
            try {
                //System.out.println(completionService.poll(2,TimeUnit.SECONDS));
                str = completionService.take().get();
                *//*if (str != null){
                    break;
                }*//*
                System.out.println("结果" + str);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                
            }
        }*/
        System.out.println("主线程执行打印结果---"+str);


        // 以下没有输出结果
        taskList.forEach(str2->{
            try {
                Future<String> take = completionService.take();
                System.out.println("线程执行结果" +take.get());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        });

    }
}
